package com.example.simin_manage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.simin_manage.admim.dto.OrderStatisticsDTO;
import com.example.simin_manage.admim.dto.Response;
import com.example.simin_manage.entity.OrderRecord;
import com.example.simin_manage.entity.PerformanceLog;
import com.example.simin_manage.entity.PerformanceRule;
import com.example.simin_manage.mapper.OrderMapper;
import com.example.simin_manage.mapper.PerformanceLogMapper;
import com.example.simin_manage.mapper.RuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/14
 */
@Service
public class OrderService extends ServiceImpl<OrderMapper, OrderRecord> {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RuleMapper ruleMapper;
    @Autowired
    private PerformanceLogMapper logMapper; // 日志表 Mapper

    // 新增/更新单量
    /**
     * 新增或更新订单，同时记录日志
     */
    public Response addOrder(OrderRecord order) {
        LocalDateTime now = LocalDateTime.now();
        order.setUpdateTime(now);

        // 查询当天该用户是否已有记录
        OrderRecord existing = baseMapper.selectOne(
                new QueryWrapper<OrderRecord>()
                        .eq("user_id", order.getUserId())
                        .eq("record_date", order.getRecordDate())
        );

        if (existing != null) {
            // 更新已有记录
            existing.setOrderCount(order.getOrderCount());
            existing.setUpdateTime(now);
            baseMapper.updateById(existing);

            // 写入日志
            PerformanceLog log = new PerformanceLog();
            log.setUserId(order.getUserId());
            log.setAction("更新订单");
            log.setDetail(String.format("%s 更新了订单，单量为 %d", order.getRecordDate(), order.getOrderCount()));
            log.setCreateTime(now);
            logMapper.insert(log);

        } else {
            // 新增记录
            order.setCreateTime(now);
            baseMapper.insert(order);

            // 写入日志
            PerformanceLog log = new PerformanceLog();
            log.setUserId(order.getUserId());
            log.setAction("新增订单");
            log.setDetail(String.format("%s 新增订单，单量为 %d", order.getRecordDate(), order.getOrderCount()));
            log.setCreateTime(now);
            logMapper.insert(log);
        }

        return new Response(200, "保存成功", null);
    }
    // 获取区间内的单量
    public Response listOrders(Long userId, String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 如果没有传日期，默认最近7天
        LocalDate end;
        LocalDate start;
        if (endDate == null || endDate.isEmpty()) {
            end = LocalDate.now();
        } else {
            end = LocalDate.parse(endDate, formatter);
        }

        if (startDate == null || startDate.isEmpty()) {
            start = end.minusDays(6); // 最近7天
        } else {
            start = LocalDate.parse(startDate, formatter);
        }

        List<OrderRecord> list = orderMapper.findByUserAndPeriod(userId, start.toString(), end.toString());
        return new Response(200, "查询成功", list);
    }
    // 计算绩效薪资
    public Response calculateSalary(Long userId, String startDate, String endDate) {
        List<OrderRecord> list = orderMapper.findByUserAndPeriod(userId, startDate, endDate);
        int totalOrders = list.stream().mapToInt(OrderRecord::getOrderCount).sum();

        // 获取对应周期规则
        PerformanceRule rule = ruleMapper.findCurrentRule(startDate, endDate);

        BigDecimal totalSalary = BigDecimal.ZERO;
        List<Map<String,Object>> breakdown = new ArrayList<>();

        for (PerformanceRule tier : ruleMapper.findByCycleId(rule.getCycleId())) {
            int min = tier.getMinOrders();
            int max = (tier.getMaxOrders() == null ? totalOrders : Math.min(totalOrders, tier.getMaxOrders()));
            int count = Math.max(0, max - min);
            if (count > 0) {
                BigDecimal salary = BigDecimal.valueOf(count)
                        .multiply(BigDecimal.valueOf(tier.getPricePerOrder()));
                totalSalary = totalSalary.add(salary);

            Map<String,Object> item = new HashMap<>();
                item.put("range", min + "-" + (tier.getMaxOrders() == null ? "以上" : max));
                item.put("rate", tier.getPricePerOrder());
                item.put("count", count);
                item.put("salary", salary);
                breakdown.add(item);
            }
        }

        Map<String,Object> result = new HashMap<>();
        result.put("totalOrders", totalOrders);
        result.put("totalSalary", totalSalary);
        result.put("breakdown", breakdown);

        return new Response(200, "计算成功", result);
    }




}
